//获取应用实例
var app = getApp();

var FormCheckRule = {
	idCardRule1: /^[0-9]{14}([0-9]|X|x)$/,
	idCardRule2: /^[0-9]{17}([0-9]|X|x)$/,
	nameRule: /^[\u4e00-\u9fa5]{2,12}$/,
	telRule: /^[1]{1}[0-9]{10}$/,
	carNbrSufRule: /^[a-zA-Z]{1}[a-zA-Z0-9]{4}[a-zA-Z0-9\u4E00-\u9FA5]{1,2}$/,

	areaNameNullMessage:"请选择户籍",
	areaAddressNullMessage:"请选择所在地区",
	checkService:"请阅读并同意《台湾通行证签注办理须知》",
	passNullMessage: "请添加通行证",
	streetNullMessage:"请输入详细地址",
	streetMinNullMessage:"详细地址不能小于5个字符",
	contactNameNullMessage:"请输入收件人姓名",
	contactNameErrorMessage:"请输入正确的收件人姓名",
	cellNumNullMessage:"请输入收件人电话",
	cellNumErrorMessage:"请输入正确的收件人电话"
};

Page({
	data: {
		visaType: 1,  //1 自由 2湖南 3 商务 4 夫妻 5 深圳  *跟后台参数同步  选择的下标
		visaName: '赴台个人旅游再次签注', //默认签注文字

		regionName: '六月一次',
		regionType: '1',
		houseIndex: [0,0,0],
		times: 1,
		bizProvinceId: '440000',  //省份ID，请求地区的种类
		isShowVisaList: false, //显示签注列表状态
		visaList:[],  //签注类别数据源
		selectedIndex: 0, //通行证滑动的下标
		isShowAMList: false,
		//省，市，区，户籍选择
		area:"请选择户籍",
		areaStyle:"color: #ababab;font-size:34rpx",
		"address.provinceId": "",
		"address.cityId": "",
		"address.countyId":"",
		"address.provinceName":"",
		"address.cityName":"",
		"address.countyName":"",
		 addressCode:"",
		locationArea: "请选择所在地区",
		locationStyle: "color: #ababab;font-size:34rpx",
		"locationAreaProvinceId": "",
		"locationAreaCityId": "",
		"locationAreaCountyId": "",
		"locationAreaProvinceName": "",
		"locationAreaCityName": "",
		"locationAreaCountyName": "",
		"address.street":"", //详情地址
		// 商务组织信息
		needInvoice:0,  //是否勾选
		sliderInvoice:false, //是否需要签注发票
		emsSitesList: [], //清远地区的紧急服务地址列表
		maskIsShow: false, //清远地区不能办理，提示mask
		emsNotAddress: '', //保存的完整收件人地址 ，用于清远地区mask
		passList: [],
    isCanScroll:true, //屏幕是否能够滑动
		isShowPoint:false, //默认取证点不显示，当选择取证方式为办事处领证就显示
		isShowFootNav:true,  //底部导航菜单
		num: 0  //订单数
	},

	/**
	 *  ajax获得签注类别
	 */
	getVisaType:function (callBack) {
		app.initTwHouse()
		app.initAddress(callBack);  //请求省市区数据
	},

	//获得通行证走马灯
	getPass: function () {
		var that = this;
		var opt = {
			url: app.globalData.host+"/wx/etw/qel.ajax",
			data: {},
			sucFn:function (result) {
				var hkmPassMsgList = [],
						passMsgList = result.body.list;
				for(var i=0;i<passMsgList.length;i++){
					var passMagList = {
						'passName': passMsgList[i].name,
						'passCode': passMsgList[i].passCode,
						'id': passMsgList[i].id,
						'validateEnd': app.toYMDDate(passMsgList[i].validateEnd),
						'birthday': app.toYMDDate(passMsgList[i].birthday),
						'passNameX': passMsgList[i].nameameX,
						'passNameM': passMsgList[i].nameM

					};
					hkmPassMsgList.push(passMagList);
				}

					that.setData({
						passList: hkmPassMsgList
					})
			}
		};
		app.ajax(opt);
	},

	onRequest: function (callBack) {
		this.getVisaType(callBack) //签注类型列表
		if(app.getStorageSync(app.globalData.twPaySuccessSign)){  //到了支付成功页首页回复默认值
				this.setData({
					visaType: 1,  //1 自由 2湖南 3 商务 4 夫妻 5 深圳  *跟后台参数同步  选择的下标
					visaName: '赴台个人旅游再次签注', //默认签注文字
					bizProvinceId: '440000',  //省份ID，请求地区的种类
					houseIndex: [0,0,0],
					isCanScroll: true,
					isShowVisaList: false,
					isShowFootNav: true,

					//省，市，区，户籍选择
					area:"请选择户籍",
					areaStyle:"color: #ababab;font-size:34rpx",
					"address.provinceId": "",
					"address.cityId": "",
					"address.countyId":"",
					"address.provinceName":"",
					"address.cityName":"",
					"address.countyName":"",
					 addressCode:"",
					 times: 1
				});
				this.getVisaType(callBack) //签注类型列表
			}
	},

	//签注发票
	switchChange: function (e) {
		var sliderInvoice = e.detail.value;
		this.setData({sliderInvoice: sliderInvoice});
	},

	//是否勾选协议
	checkTap:function (e) {
		var needInvoice = e.target.dataset.agree;
		if(needInvoice==0){
			needInvoice = 1;
		}else{
			needInvoice = 0;
		}
		this.setData({needInvoice: needInvoice});
	},

	//分享功能
	onShareAppMessage: function () {
		return {
			title: '赴台通行证签注办理',
			desc: '赴台通行证签注办理',
			path: '/pages/twHandle/twHandle'
		}
	},

	onLaunch: function(options) {
	},

	getCategory: function () {
		var that = this;
		var opt2 = {
			url: app.globalData.host+"/wx/etw/qcbl.ajax",
			data: {},
			sucFn:function (result) {
				that.setData({
					visaList: result.body.chargeRuleList
				})
			}
		};
		app.ajax(opt2);
	},

	onLoad: function () {
		
	},

	onShow:function () {
		var that = this;
		//获得订单数
		app.getOrderNum(function (num,openId){
			that.onRequest(function () {   //所在地址数据确定完全请求完，在赋值缓存，解决先取缓存，再恢复成默认值
				var page = app.getStorageSync(app.globalData.cacheTWData);
				that.setData(Object.assign({},page,
					app.getStorageSync('twAddPass')? {
							selectedIndex: app.getStorageSync('twAddPass')?0:that.data.selectedIndex
						}:{},
						{num: num}
				));

				that.getPass()  //通行证走马灯列表
				that.getCategory()  //签注类别
			}); 
		})

		app.setStorageSync(app.globalData.callVisaSign,1)  //用于港澳首页是否调用签注类别标记，不请求签注类型和不更新签注类别
	},

	//底部切换页面方法
	toUrl:function (e) {
		var url = e.currentTarget.dataset.url;
		if(url!='/pages/twHandle/twHandle'){
			if(url == ''){
				//develop（开发版），trial（体验版），release（正式版）
				var res = {
					appid: app.globalData.appid,
					path: '',
					envVersion: app.globalData.envVersion
				}
				app.crossToUrl(res)
			}else {
				app.redirectTo({url: url});
			}
		}
	},
	cacheData:function () {
		app.setStorageSync(app.globalData.cacheTWData,Object.assign({},this.data,{ popErrorMsg: '' },{errorScrollIntoViewName: ''},
			{errorFocusName:''},{isCanScroll: true})); //保存状态在缓存

		app.removeStorage('twAddPass') //添加通行证保存的缓存，当用户保存通行证返回页面走马灯应该滑动到添加的位置
		app.removeStorage(app.globalData.twPaySuccessSign);  //支付成功页标记

		app.removeStorageSync(app.globalData.twCallVisaSign);  //是否需要调用签注类别
	},

	onUnload:function () {
		this.cacheData()
	},

	onHide:function () {
		this.cacheData()
	},
	//确认提交按钮
  formSubmit:function(e){
		var formData = e.detail.value;
		var street = formData['address.street'];
		var provinceId = formData['address.provinceId']; //户籍
	  var recipientName = formData.recipientName; //收件姓名
	  var cardNumber = formData.cardNumber; //收件人电话号码
		var locationAreaProvinceId = formData['locationAreaProvinceId'];//收件人地址
		var needInvoice = formData.needInvoice; //协议
		var pageObj = this;
		var currentPass=this.data.passList[this.data.selectedIndex];

	  var address={
		  id: formData.locationAreaProvinceId,  //地址id，数据库主键标识
		  provinceId: formData.locationAreaProvinceId,   //省份id
		  cityId: formData.locationAreaCityId, //地市id
		  countyId: formData.locationAreaCountyId,//区县id  441825 不能办理
		  street: formData["address.street"], //街道详细地址
		  fullAddr: formData.locationAreaProvinceName+formData.locationAreaCityName+formData.locationAreaCountyName, //'广东省清远市 连山壮族瑶族自治县 我们自己都江堵救灾', //完整地址
		  contactName: formData.recipientName, //收件人
		  cellNum: formData.cardNumber  //收件人联系号码

	  };

	  if(currentPass == undefined){  //判断通行证是否为空
	  	app.errorToast(FormCheckRule.passNullMessage);
		  pageObj.setData({scrollTop: 0})
		  return;
	  }

	  var flag = app.check([
		  {
			  value: provinceId,
			  errorFocusName:"provinceId",
			  errorScrollIntoViewName:"areaInfo",
			  fn: function(value){
				  if(value == ''){
					  app.errorToast(FormCheckRule.areaNameNullMessage);
					  return false;
				  }else {
					  return true;
				  }
			  }
		  }
	  ]);
	  if (!flag) {
		  return false;
	  }

	  /*
	   *  个人自由行类型
	   * */

	 if(recipientName==''){  //收件人姓名
		 this.setData({
		  errorScrollIntoViewName:"addressSign",
		  errorFocusName: "recipientName"
		 });
		 app.errorToast(FormCheckRule.contactNameNullMessage);
		 return;
	 }else if(!FormCheckRule.nameRule.test(recipientName)){//收件人姓名
		 pageObj.setData({
			 errorScrollIntoViewName:"addressSign",
		   errorFocusName: "recipientName"
		 });
		 app.errorToast(FormCheckRule.contactNameErrorMessage);
		 return;
	 }else if(cardNumber==''){ //收件人手机号码
		 pageObj.setData({
			 errorScrollIntoViewName:"addressSign",
		   errorFocusName: "contactNumber"
		 });
		 app.errorToast(FormCheckRule.cellNumNullMessage);
		 return;
	 }else if(!FormCheckRule.telRule.test(cardNumber)){//收件人手机号码
		 pageObj.setData({
			 errorScrollIntoViewName:"addressSign",
			 errorFocusName: "contactNumber"
		 });
		 app.errorToast(FormCheckRule.cellNumErrorMessage);
	 }else if(locationAreaProvinceId==''){  //收件人所在地
		 pageObj.setData({
			 errorScrollIntoViewName:"addressSign",
		 })
		 app.errorToast(FormCheckRule.areaAddressNullMessage);
		 return;
	 } else if(street==''){
		 this.setData({
			 errorScrollIntoViewName:"addressSign",
		   errorFocusName:'street'
		 });
		 app.errorToast(FormCheckRule.streetNullMessage);
		 return;
	   }else if(street.length<5){  //详细地址
		 this.setData({
			 errorScrollIntoViewName:"addressSign",
			 errorFocusName:'street'
		 });
		 app.errorToast(FormCheckRule.streetMinNullMessage);
		 return;
	 }else if(needInvoice==0){		 //是否勾选协议
		 app.errorToast(FormCheckRule.checkService);
		  this.setData({
			  errorScrollIntoViewName: "organizationAddress"
		  })
		  return;
	  }

	  console.log(this.data)
	  var enObj = "";
	  enObj = {
		  type: this.data.visaType,
		  passId: currentPass.id, //证件id,
		  passCode: currentPass.passCode, //证件号码
		  passName: currentPass.passName,  //证件人名称
		  passNameX: currentPass.passNameX,  //证件人名称，姓
		  passNameM: currentPass.passNameM,  //证件人名称，名
		  bizProvinceId: this.data.bizProvinceId,  //签注类型省份ID
		  provinceId: formData['address.provinceId'], //省份ID
		  cityId: formData['address.cityId'], //户籍所属城市ID
		  birthday: currentPass.birthday, //生日
		  validateEnd: currentPass.validateEnd, //有效期
		  birthPlace:formData['address.provinceName']+formData['address.cityName']+formData['address.countyName'], //户籍所在地+++
		  birthCode: this.data.addressCode,

		  times: this.data.times,

		  linkTel: formData.cardNumber,
		  needInvoice: this.data.sliderInvoice?1:0 //是否需要发票  1-需要 0-不需要
	  };

	  var post = {
		  endorseInfoList: [{
			  "endorseInfoObj": JSON.stringify(enObj),
			  "address": JSON.stringify(address)
		  }]
	  };
	  var formResult = {
		  objStr: JSON.stringify(post)
	  };

	  var opt = {
		  url: app.globalData.host+"/wx/etw/handling.ajax",
		  data: formResult,
		  sucFn:function (result) {
		  	if(!result.body.canHandler){
				  pageObj.setData({
					  emsSitesList: result.body.emsSites,
					  emsNotAddress : address.fullAddr,
					  maskIsShow: true
				  })
			  }else {
				  result['payData']= formResult.objStr;
				  app.setStorageSync(app.globalData.twCacheOrderPay, result.body);
				  app.navigateTo({url:'../twPayment/twPayment'});
			  }

		  }
	  };
	  app.ajax(opt);
	},

	//说明内容
	agreeTap:function (e) {
		//visaType: tw *跟后台参数同步  选择的下标
		app.navigateTo({url:'../agreement/agreement?isNoticeShow='+'tw'})
	},

	//输入框公用方法
	infoInput: function(e){
		var id = e.currentTarget.id,
	      value = e.detail.value;
		 if(id == "recipientName"){  //收件人姓名
			var recipientName = value.replace(/(^\s*)|(\s*$)/g,"");
			this.setData({recipientName: recipientName});
			if (recipientName==''||FormCheckRule.nameRule.test(recipientName)) {
				this.setData({recipientNameIconType: "success"});
			} else if (value.length > 0) {
				this.setData({recipientNameIconType: "error"});
			}else {
				this.setData({recipientNameIconType: ""});
			}
		}else if(id == "contactNumber"){ //收件人联系电话
			value = value.substr(0, 11);
			var contactNumber = value.replace(/(^\s*)|(\s*$)/g,"");
			this.setData({contactNumber: contactNumber});
			if (contactNumber==''||FormCheckRule.telRule.test(contactNumber)) {
				this.setData({urgentLinkTelIconType: "success"});
			} else if (value.length > 0) {
				this.setData({urgentLinkTelIconType: "error"});
			} else {
				this.setData({urgentLinkTelIconType: ""});
			}

		}else if(id == "address.street"){ //详细信息
			var street = value.replace(/(^\s*)|(\s*$)/g,"");
			this.setData({"address.street": street});
			if(street==''||value.length>4){
				this.setData({streetNameIconType: "success"});
			} else if(value.length>0){
				this.setData({streetNameIconType: "error"})
			}else {
				this.setData({streetNameIconType: ""})
			}
		}
	},

	//滑动获取通行证走马灯下标
	sliderChange: function (e) {
		this.setData({
			selectedIndex: e.detail.current
		})
	},

	//点击通行证跳入通行证页
	sliderToUrl: function (e) {
		app.navigateTo({url:'../twAddpass/twAddpass?id='+e.currentTarget.dataset.id+'&type='+e.currentTarget.dataset.type})
	},

	//回复默认状态
	//this.isClickVisaType true为点击获取签注类型，false 为接口默认取一个签注类型
	/*选择签注类别列表 start*/
	//选择签注类别列表
  showVisaListTap: function(e){
	  this.setData({
		  isCanScroll: true,
		  isShowVisaList: false,
		  isShowFootNav: true,

		  visaName: e.target.dataset.name,
		  visaType: e.target.dataset.type,
		  bizProvinceId: e.target.dataset.provinceid,
		  times: e.target.dataset.times,

		  regionName: e.target.dataset.timesname,
		  regionType: e.target.dataset.type,
		  houseIndex: [0,0,0],
		  //省，市，区，户籍选择
		  area:"请选择户籍",
		  areaStyle:"color: #ababab;font-size:34rpx",
		  "address.provinceId": "",
		  "address.cityId": "",
		  "address.countyId":"",
		  "address.provinceName":"",
		  "address.cityName":"",
		  "address.countyName":""
	  });
	  //赴台签注切换签注类别 ，传不同的类型，获得不同城市
	   app.initTwHouse();
	},

	//点击签注图标显示旅游签注类别列表
	visaSelection: function(e){
		var that = this;
		setTimeout(function(){
			that.setData({
				isCanScroll:false,
				isShowVisaList: true,
				isShowFootNav: false
			});
		},50)
	},

	//点击mask隐藏旅游签注类别列表
	hideVisaSelection: function(){
		this.setData({
			isCanScroll:true,
			isShowVisaList: false,
			isShowFootNav: true
		});
	},

	//选择城市取消按钮
	cancelAddressTap:function (e) {
		this.setData({
			isAddressShow: false,
			isShowFootNav: true
		});
	},

	//显示地址组件
	areaTap:function (e) {
		this.setData({
			isAddressShow: true,
			isShowFootNav: false
		});
	},

	// 收件人地址组件start
	//显示收件人地址组件
	locationTap: function (e) {
		this.setData({
			isLocationShow: true,
			isShowFootNav: false
		});
	},

	//选择收件人取消按钮
	cancelLocationTap:function (e) {
		this.setData({
			isLocationShow: false,
			isShowFootNav: true
		});
	},

	//隐藏清远地区提示框mask
	hideMask: function (e) {
		this.setData({
			maskIsShow: false
		})
	},

	//选择收件人确定按钮
	confirmLocationTap: function (e) {
		var current_value = this.data.value;
		var provinceName = this.data.proviceData[current_value[0]].name;
		var cityName = this.data.cityData[current_value[1]].name;
		var countyName = "";
		if(this.data.districtData[current_value[2]].name!=null){
			countyName = this.data.districtData[current_value[2]].name;
		}

		this.setData({
			isShowFootNav:true,
			isLocationShow: false
		})

		this.setData({
			locationStyle:"color:#1a1a1a;font-size:34rpx",
			locationArea:provinceName+cityName+countyName,
			"locationAreaProvinceId":this.data.proviceData[current_value[0]].id,
			"locationAreaCityId":this.data.cityData[current_value[1]].id,
			"locationAreaCountyId":this.data.districtData[current_value[2]].id,
			"locationAreaProvinceName":provinceName,
			"locationAreaCityName":cityName,
			"locationAreaCountyName":countyName
		});
	},
	// 收件人地址组件end

	//选择户籍城市确定按钮
	confirmTWAddressTap:function (e) {
				var twHouseProviceData = this.data.twHouseProviceData;
 	    	var twHouseCityData = this.data.twHouseCityData;
 	    	var cityIndex = this.data.houseIndex;
				var proviceData = twHouseProviceData[cityIndex[0]];
				var cityData = twHouseCityData[cityIndex[1]];
				console.log(cityData.code)
        this.setData({
	        //省，市，区，户籍选择
	        isShowFootNav: true,
	        isAddressShow: false,
	        area:proviceData.name+cityData.name,
	        areaStyle:"color:#1a1a1a;font-size:34rpx",
	        "address.provinceId": proviceData.id,
	        "address.cityId": cityData.cityId,
	        "address.provinceName": proviceData.name,
	        "address.cityName": cityData.name,
		       addressCode: cityData.code
        });
	},

	//户籍省市区滑动事件
  bindTWHouseChange: function (e) {
		app.bindTWHouseChange(e);
	},

	//地址省市区滑动事件
	bindAddressChange: function (e) {
		app.bindAddressChange(e);
	}
});
